import logging
from datetime import datetime
import pendulum
import requests


def get_message_data(page):
    all_message = []
    while True:
        if page.s_ele('已经到顶啦'):
            break
        page('.messageList').scroll.to_top()
        page.wait(1)
    kehu_name = page.s_ele('text=用户昵称：').child(1).text
    message_list = page.s_eles('@style=align-self: stretch;')
    for message in message_list:
        message_row = {
            'UserType': '',
            'UserName': '',
            'RecordTime': '',
            'Content': '',
        }
        kehu_message = message.s_ele('.iD7SHBvMhm4OhfCsBGr1 leaveMessage messageNotMe')
        kefu_message = message.s_ele('.iD7SHBvMhm4OhfCsBGr1 leaveMessage messageIsMe')
        kehu_img = message.s_ele(r'@style=position: relative; display: flex; flex-direction: row;')
        kefu_img = message.s_ele(r'@style=position: relative; display: flex; flex-direction: row-reverse;')
        system_message = message.s_ele(
            '.chatd-text chatd-text--breakWord chatd-text--truncate chatd-card-header-content')
        time_message = message.s_ele('.O4UWWFoQxgMq4AWHMq25 Msmyl5BHIkq2JmFI3Bbg')
        if kehu_message and kehu_message.text != '':
            message_row['UserType'] = 0
            message_row['UserName'] = kehu_name
            message_row[
                'RecordTime'] = time_message.text if '昨天' not in time_message.text else pendulum.now().subtract(
                days=1).strftime('%m月%d日 ') + time_message.text.replace('昨天 ', '')
            message_row['Content'] = kehu_message.text
            all_message.append(message_row)
        if kehu_img and not kehu_message:
            img = kehu_img.child(1)
            if img and img.attr("src"):
                src = img.attr("src")
                message_row['UserType'] = 0
                message_row['UserName'] = kehu_name
                message_row[
                    'RecordTime'] = time_message.text if '昨天' not in time_message.text else pendulum.now().subtract(
                    days=1).strftime('%m月%d日 ') + time_message.text.replace('昨天 ', '')
                message_row['Content'] = src
                all_message.append(message_row)
        if kefu_message:
            kefu_name_ele = message.s_ele('.XKc_5xgSwz4XGLjzWOGa')
            message_row['UserType'] = 1
            message_row['UserName'] = kefu_name_ele.text if kefu_name_ele else '客服(连续消息)'
            message_row[
                'RecordTime'] = time_message.text if '昨天' not in time_message.text else pendulum.now().subtract(
                days=1).strftime('%m月%d日 ') + time_message.text.replace('昨天 ', '')
            message_row['Content'] = kefu_message.text
            all_message.append(message_row)
        if kefu_img and not kefu_message:
            img = kefu_img.child(1)
            if img and img.attr("src"):
                src = img.attr("src")
                kefu_name_ele = message.s_ele('.XKc_5xgSwz4XGLjzWOGa')
                message_row['UserType'] = 1
                message_row['UserName'] = kefu_name_ele.text if kefu_name_ele else '客服(连续消息)'
                message_row[
                    'RecordTime'] = time_message.text if '昨天' not in time_message.text else pendulum.now().subtract(
                    days=1).strftime('%m月%d日 ') + time_message.text.replace('昨天 ', '')
                message_row['Content'] = src
                all_message.append(message_row)
        if system_message:
            message_row['UserType'] = 3
            message_row['UserName'] = '系统消息'
            message_row[
                'RecordTime'] = time_message.text if '昨天' not in time_message.text else pendulum.now().subtract(
                days=1).strftime('%m月%d日 ') + time_message.text.replace('昨天 ', '')
            message_row['Content'] = system_message.text
            all_message.append(message_row)
    return all_message


def 获取聊天数据并上传ERP(page, shop_name):
    page.get('https://fxg.jinritemai.com/ffa/eco/experience-score/detail?nodeId=307')
    page.wait.ele_displayed('text=会话分析')
    page('text=会话分析').click()
    page.wait(5)
    while True:
        if not page.s_ele('.v8_subtitle_OeV2F'):
            logging.info('客服不满意没有数据')
            break
        trs = page('.auxo-table-tbody').eles('t:tr')
        for tr in trs:
            date = (f'{datetime.now().year}/' + tr.child(1)('.v8_subtitle_OeV2F').text.split('-')[0]).replace('/', '-')
            date_datetime = datetime.strptime(date, '%Y-%m-%d %H:%M')
            yesterday = (pendulum.now().subtract(days=1).set(hour=0, minute=0, second=0, microsecond=0).replace(tzinfo=None))
            logging.info(date)
            logging.info(yesterday)
            if date_datetime < yesterday:
                return
            tr.child(5).ele('text=查看会话').click(by_js=True)
            page.wait(1)
            tab = page.get_tab(page.latest_tab)
            tab.wait.ele_displayed('text=查看会话', timeout=10)
            tab.wait(2)
            tab('text=查看会话').click(by_js=True)
            tab.wait(1)
            all_message = get_message_data(tab)
            会话ID = tab('.h9hhLvd04jbunCS5IP7D').text.replace('ID：', '')
            账号名称 = tab('@data-qa-id=qa-history-conversation-item').child(3).text
            data = [{
                'OrderNo': 会话ID,
                'CreatedTime': date,
                'Platform': 6,  # 抖音平台枚举
                'ShopName': shop_name,
                'ChatAccount': 账号名称,
                'ChatInfoList': all_message
            }]
            url = 'http://192.168.16.240:8001/api/Customerservice/UnPayOrder/BatchAddReplyCarelesslyAsync'
            # url = 'http://95qmvu.natappfree.cc/api/Customerservice/UnPayOrder/BatchAddReplyCarelesslyAsync'
            while True:
                res = requests.post(url, json=data)
                if res.status_code == 200:
                    break
            logging.info(res.text)
            tab.close()
        if page('.anticon anticon-right').parent(1).states.is_enabled:
            page('.anticon anticon-right').click()
            logging.info('下一页')
            page.wait(3)
        else:
            logging.info('最后一页')
            break
